package com.umbrella.worker.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.umbrella.worker.dao.WContactMapper;
import com.umbrella.worker.dao.WMemberAccountRecordMapper;
import com.umbrella.worker.dao.WMemberCouponMapper;
import com.umbrella.worker.dao.WMembersMapper;
import com.umbrella.worker.dao.WOrderMapper;
import com.umbrella.worker.dto.ContactDO;
import com.umbrella.worker.dto.MemberCouponDO;
import com.umbrella.worker.dto.MembersDO;
import com.umbrella.worker.entity.WContact;
import com.umbrella.worker.entity.WContactExample;
import com.umbrella.worker.entity.WMemberAccountRecord;
import com.umbrella.worker.entity.WMemberAccountRecordExample;
import com.umbrella.worker.entity.WMemberCoupon;
import com.umbrella.worker.entity.WMemberCouponExample;
import com.umbrella.worker.entity.WMembers;
import com.umbrella.worker.entity.WMembersExample;
import com.umbrella.worker.entity.WMembersExample.Criteria;
import com.umbrella.worker.entity.WOrderExample;
import com.umbrella.worker.query.MembersQuery;
import com.umbrella.worker.result.ResultDO;
import com.umbrella.worker.result.ResultSupport;
import com.umbrella.worker.service.IMemberService;
import com.umbrella.worker.util.BeanUtilsExtends;
import com.umbrella.worker.util.StringUtil;

@Service("memberService")
public class MemberServiceImpl  extends BaseServiceImpl implements IMemberService {
	
	private static Logger logger = Logger.getLogger(MemberServiceImpl.class);
	
	@Autowired
	private WMembersMapper membersMapper;
	
	@Autowired
	private WMemberCouponMapper memberCouponMapper;
	
	@Autowired
	private WContactMapper contactMapper;
	
	@Autowired
	private WOrderMapper orderMapper;
	@Autowired
	private WMemberAccountRecordMapper memberAccountRecordMapper;

	@Override
	public ResultDO create(MembersDO membersDO) {
		
		WMembers members = new WMembers();
		
		ResultSupport result = BeanUtilsExtends.copy(members, membersDO);
		
		if(!result.isSuccess()) {
			return result;
		}
		
		int recordNum = -1;
		
		members.setwMRegTime(Calendar.getInstance().getTime());
		members.setDatalevel(1);
		members.setStatus(1);
		members.setCreateTime(Calendar.getInstance().getTime());
		members.setModifiTime(Calendar.getInstance().getTime());
		
		try {
			recordNum = membersMapper.insertSelective(members);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			logger.error("[obj:catalogs][opt:create][msg:" + e.getMessage()
			+ "]");
			return result;
		}
		
		if(recordNum < 1) {
			result.setSuccess(false);
			return result;
		}
		
		result.setModel(ResultDO.FIRST_MODEL_KEY, members.getId());
		
		return result;
	}

	@Override
	public ResultDO validate(MembersDO membersDO) {
		
		ResultSupport result = new ResultSupport();
		
		WMembersExample example = new WMembersExample();
		
		example.createCriteria()
			.andWMMobileEqualTo(membersDO.getwMMobile())
			.andWMPasswordEqualTo(membersDO.getwMPassword())
			.andDatalevelNotEqualTo(-1);
		List<WMembers> list = null;
		try {
			list = membersMapper.selectByExample(example);
		} catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
            result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
            logger.error("[obj:member][opt:login][msg:"+e.getMessage()+"]");
            return result;
		}
		
		
		if(list.size() == 1) {
			membersDO = getMemberDO(list.get(0));
			if(membersDO != null) {
				result.setModel(ResultSupport.FIRST_MODEL_KEY, membersDO);
			} else {
				result.setSuccess(false);
				result.setErrorCode(ResultDO.MEMBER_LOGIN_FAILED);
	            result.setErrorMsg(ResultDO.MEMBER_LOGIN_FAILED_MSG);
				return result;
			}
		} else {
			result.setSuccess(false);
			result.setErrorCode(ResultDO.MEMBER_LOGIN_FAILED);
            result.setErrorMsg(ResultDO.MEMBER_LOGIN_FAILED_MSG);
			return result;
		}
		
		return result;
	}
	
	@Override
	public ResultDO isMobileReg(MembersQuery membersQuery) {
		
		ResultSupport result = new ResultSupport();
		
		WMembersExample example = new WMembersExample();
		WMembersExample.Criteria c = example.createCriteria();
		
		if(StringUtil.isNotEmpty(membersQuery.getMobile())) {
			c.andWMMobileEqualTo(membersQuery.getMobile());
		}
		
		int recordNum = -1;
		try {
			recordNum = membersMapper.countByExample(example);
		} catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
            result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
            logger.error("[obj:member][opt:login][msg:"+e.getMessage()+"]");
            return result;
		}
		
		if(recordNum > 0) {
			result.setSuccess(false);
		}
		
		return result;
	}
	
	@Override
	public ResultDO modifiPwd(MembersDO membersDO) {
		
		ResultSupport result = new ResultSupport();
		
		WMembersExample example = new WMembersExample();
		
		Criteria c = example.createCriteria();
		
		if(StringUtil.isGreatOne(membersDO.getId())) {
			c.andIdEqualTo(membersDO.getId());
			c.andWMPasswordEqualTo(membersDO.getOldPassword());
		}
		
		if(StringUtil.isNotEmpty(membersDO.getwMMobile())) {
			c.andWMMobileEqualTo(membersDO.getwMMobile());
		}
	
		List<WMembers> list = null;
		try {
			list = membersMapper.selectByExample(example);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
			logger.error("[obj:members][opt:modifi][msg:" + e.getMessage()
					+ "]");
			return result;
		}
		
		if(list.size() < 1) {
			result.setSuccess(false);
			return result;
		}
		WMembers members = new WMembers();
		
		result = BeanUtilsExtends.copy(members, membersDO);
		// 拷贝失败
		if (!result.isSuccess()) {
			return result;
		}
		members.setModifiTime(Calendar.getInstance().getTime());
		int recordNum = -1;
		
		try {
			recordNum = membersMapper.updateByExampleSelective(members, example);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
			logger.error("[obj:members][opt:modifi][msg:" + e.getMessage()
					+ "]");
			return result;
		}
		
		if (recordNum < 1) {
			result.setSuccess(false);
		}
		return result;
	}

	
	@Override
	public ResultDO remove(Integer memberId) {
		
		ResultSupport result = new ResultSupport();
		
		WMembers members = new WMembers();
		
		if(StringUtil.isGreatOne(memberId)) {
			members.setId(memberId);
		} else {
		    result.setSuccess(false);
		    return result;
		}
		members.setDatalevel(-1);
		int recordNum = -1;
		try {
			recordNum = membersMapper.updateByPrimaryKeySelective(members);
		} catch (Exception e) {
			result.setSuccess(false);
	        result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
	        result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
	        logger.error("[obj:member][opt:remove][msg:"+e.getMessage()+"]");
	        return result;
		}
		if (recordNum != 1) {
			result.setSuccess(false);
			return result;
		}
		
		return result;
	}

	@Override
	public ResultDO get(Integer memberId) {
		
		ResultSupport result = new ResultSupport();
		
		WMembers members = null;
		if(!StringUtil.isGreatOne(memberId)) {
			 result.setSuccess(false);
			 return result;
		} 
		
		try {
			members = membersMapper.selectByPrimaryKey(memberId);
		} catch (Exception e) {
			result.setSuccess(false);
	        result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
	        result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
	        logger.error("[obj:member][opt:get][msg:"+e.getMessage()+"]");
	        return result;
		}
		
		MembersDO membersDO = getMemberDO(members);
		
		if(membersDO == null) {
			result.setSuccess(false);
	        result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
	        result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
			return result;
		}
				
		WMemberCouponExample example = new WMemberCouponExample();
		example.createCriteria().andWMcMemberIdEqualTo(memberId).andStatusEqualTo(1);
		
		List<MemberCouponDO> memberCouponDOList = null;
		try {
			List<WMemberCoupon> list = memberCouponMapper.selectByExample(example);
			memberCouponDOList = getMemberCouponDOList(list);
		} catch (Exception e) {
			result.setSuccess(false);
	        result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
	        result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
	        logger.error("[obj:memberCoupon][opt:get][msg:"+e.getMessage()+"]");
	        return result;
		}
		
		if(memberCouponDOList != null) {
			membersDO.setCouponsCount(memberCouponDOList.size());
			membersDO.setMemberCoupons(memberCouponDOList);
		} else {
			membersDO.setCouponsCount(0);
		}
		
		
		WContactExample wcex = new WContactExample();
		wcex.createCriteria().andWCMembersIdEqualTo(memberId);
		
		List<ContactDO> contactDOList = null;
		try {
			List<WContact> list = contactMapper.selectByExample(wcex);
			contactDOList = getContactDOList(list);
		} catch (Exception e) {
			result.setSuccess(false);
	        result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
	        result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
	        logger.error("[obj:memberCoupon][opt:get][msg:"+e.getMessage()+"]");
	        return result;
		}
		
		if(contactDOList != null) {
			membersDO.setContacts(contactDOList);
		} 
		
		WOrderExample woex = new WOrderExample();
		WOrderExample.Criteria c = woex.createCriteria();
		
		
		c.andWOMembersIdEqualTo(memberId).andDatalevelEqualTo(1);
		int count;
		try {
			count = orderMapper.countByExample(woex);
		} catch (Exception e) {
			result.setSuccess(false);
	        result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
	        result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
	        e.printStackTrace();
	        logger.error("[obj:member][opt:get][msg:"+e.getMessage()+"]");
	        return result;
		}
		
		membersDO.setOrderCount(count);
		result.setModel(ResultSupport.FIRST_MODEL_KEY, membersDO);
		
		return result;
	}

	@Override
	public ResultDO list(MembersQuery membersQuery) {
		
		ResultSupport result = new ResultSupport();
		
		WMembersExample example = new WMembersExample();
		WMembersExample.Criteria c = example.createCriteria();
		
		if(StringUtil.isNotEmpty(membersQuery.getMobile())) {
			c.andWMMobileLike("%" +membersQuery.getMobile()+ "%");
		}
		
		if(StringUtil.isNotEmpty(membersQuery.getOrderByClause())) {	
			example.setOrderByClause(" " + membersQuery.getOrderByClause() + " " + membersQuery.getSort());
		} else {
			example.setOrderByClause(" CREATE_TIME DESC");
		}
		
		if(membersQuery.isPage()) {
			long count = 0;
			try {
				count = membersMapper.countByExample(example);
			} catch (Exception e) {
				result.setSuccess(false);
		        result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
		        result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
		        e.printStackTrace();
		        logger.error("[obj:member][opt:get][msg:"+e.getMessage()+"]");
		        return result;
			}
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
			int pageNO = membersQuery.getPageNO();
			if(pageNO > 0) {
				pageNO = pageNO -1;
			}
			String pageByClause = " limit " + (pageNO * membersQuery.getPageRows())
					+ "," + membersQuery.getPageRows();
			
			example.setPageByClause(pageByClause);
		}
		
		List<WMembers> list = null;
		
		try {
			list = membersMapper.selectByExample(example);
		} catch (Exception e) {
			result.setSuccess(false);
	        result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
	        result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
	        logger.error("[obj:member][opt:get][msg:"+e.getMessage()+"]");
	        return result;
		}
		
		List<MembersDO> memberList = getMemberDOList(list);
		
		List<MembersDO> lists = new ArrayList<MembersDO>();
		
		if(memberList!=null){
			for(int i = 0; i < memberList.size(); i++) {
				MembersDO member = memberList.get(i);
				if(member != null) {
					//查询联系信息 地址
					WContactExample contact=new WContactExample();
					WContactExample.Criteria con = contact.createCriteria();
					if(StringUtil.isGreatOne(member.getId())){
						con.andWCMembersIdEqualTo(member.getId());
					}
					List<WContact> conts=contactMapper.selectByExample(contact);
					List<ContactDO> conts2=getContactDOList(conts);
					member.setContacts(conts2);
					//统计总的消费金额
					 WMemberAccountRecordExample record=new WMemberAccountRecordExample();
					 WMemberAccountRecordExample.Criteria recor = record.createCriteria();
					 if(StringUtil.isGreatOne(member.getId())){
						 recor.andWMemberIdEqualTo(member.getId());
					 }
					 BigDecimal totals=new BigDecimal(0);
					 List<WMemberAccountRecord> records=memberAccountRecordMapper.selectByExample(record);
					 if(records!=null){
						 for (WMemberAccountRecord wMemberAccountRecord : records) {
							 totals.add(wMemberAccountRecord.getwUseMoney());
						}
					 }
					 member.setCountAmount(totals);
					lists.add(member);
				}
			}
		}
		result.setModel(ResultSupport.FIRST_MODEL_KEY, lists);
		
		return result;
	}
	
	public ResultDO createCoupon(MemberCouponDO memberCouponDO) {
		
		WMemberCoupon memberCoupon = new WMemberCoupon();
		
		ResultSupport result = BeanUtilsExtends.copy(memberCoupon, memberCouponDO);
		
		if(!result.isSuccess()) {
			return result;
		}
		
		int recordNum = -1;
		memberCoupon.setModifiAuthor(memberCoupon.getCreateAuthor());
		memberCoupon.setwCCouponNo(getCouponNO());
		memberCoupon.setDatalevel(1);
		memberCoupon.setStatus(1);
		memberCoupon.setCreateTime(Calendar.getInstance().getTime());
		memberCoupon.setModifiTime(Calendar.getInstance().getTime());
		
		
		try {
			recordNum = memberCouponMapper.insertSelective(memberCoupon);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			logger.error("[obj:catalogs][opt:create][msg:" + e.getMessage()
			+ "]");
			return result;
		}
		
		if(recordNum < 1) {
			result.setSuccess(false);
			return result;
		}
		
		result.setModel(ResultDO.FIRST_MODEL_KEY, memberCoupon.getId());
		
		return result;
	}
	
	@Override
	public ResultDO getCoupon(int id) {
		
		ResultSupport result = new ResultSupport();
		
		WMemberCoupon memberCoupon = null;
		if(!StringUtil.isGreatOne(id)) {
			 result.setSuccess(false);
			 return result;
		} 
		
		try {
			memberCoupon = memberCouponMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			result.setSuccess(false);
	        result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
	        result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
	        logger.error("[obj:supplier][opt:get][msg:"+e.getMessage()+"]");
	        return result;
		}
		
		MemberCouponDO memberCouponDO = getMemberCouponDO(memberCoupon);
		if(memberCouponDO != null) {
			result.setModel(ResultSupport.FIRST_MODEL_KEY, memberCouponDO);
		} else {
			result.setSuccess(false);
	        result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
	        result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
			return result;
		}
		
		return result;
	}
	
	
	public ResultDO memberCouponList(Integer memberId) {
		
		ResultSupport result = new ResultSupport();
		
		WMemberCouponExample example = new WMemberCouponExample();
		example.createCriteria().andWMcMemberIdEqualTo(memberId).andStatusEqualTo(1);
		
		List<WMemberCoupon> memberCouponList = null;
		try {
			memberCouponList = memberCouponMapper.selectByExample(example);
		} catch (Exception e) {
			result.setSuccess(false);
	        result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
	        result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
	        logger.error("[obj:supplier][opt:get][msg:"+e.getMessage()+"]");
	        return result;
		}
		
		List<MemberCouponDO> mcList = getMemberCouponDOList(memberCouponList);
		
		result.setModel(ResultSupport.FIRST_MODEL_KEY, mcList);
		
		return result;
	}
	
	
	public ResultDO verification(Integer id) {
		ResultSupport result = new ResultSupport();
		WMemberCoupon memberCoupon = new WMemberCoupon();
		memberCoupon.setId(id);
		memberCoupon.setStatus(2);
		memberCoupon.setModifiAuthor("system");
		memberCoupon.setModifiTime(Calendar.getInstance().getTime());
		int recordNum = -1;
		try {
			recordNum = memberCouponMapper.updateByPrimaryKeySelective(memberCoupon);
		} catch (Exception e) {
			result.setSuccess(false);
	        result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
	        result.setErrorMsg(ResultDO.SYSTEM_EXCEPTION_ERROR_MSG);
	        logger.error("[obj:supplier][opt:get][msg:"+e.getMessage()+"]");
	        return result;
		}
		if (recordNum != 1) {
			result.setSuccess(false);
			return result;
		}
	
		return result;
	}
	
	private String getCouponNO() {
		String couponNO = System.currentTimeMillis() + UUID.randomUUID().hashCode() + "";
		return couponNO;
	}

}
